import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { MongooseModule } from '@nestjs/mongoose';
import { ConfigModule, ConfigService } from '@nestjs/config';
import * as path from 'path';
import { ArticleModule } from './modules/article/article.module';
import { APP_FILTER } from '@nestjs/core';
import { HttpExceptionFilter } from './filters/http-exception.filter';
import { MongooseExceptionFilter } from './filters/mongoose-exception.filter';
import { MongodbExceptionFilter } from './filters/mongodb-exception.filter';
import { UnknowExceptionFilter } from './filters/unknow-exception.filter';
const ENV = process.env.NODE_ENV || 'development';
const devEnvFilePath = 'env/.env.' + ENV;

@Module({
  imports: [
    ConfigModule.forRoot({
      isGlobal: true,
      expandVariables: true,
      envFilePath: [path.join(__dirname, devEnvFilePath)],
      ignoreEnvFile: ENV == 'production' ? true : false,
    }),
    MongooseModule.forRootAsync({
      imports: [ConfigModule],
      inject: [ConfigService],
      useFactory: async (configService: ConfigService) => ({
        uri: configService.get('MONGO_URI'),
        connectionFactory: (connection) => {
          return connection;
        },
      }),
    }),
    ArticleModule,
  ],
  controllers: [AppController],
  providers: [
    AppService,
    {
      provide: APP_FILTER,
      useClass: UnknowExceptionFilter,
    },
    {
      provide: APP_FILTER,
      useClass: HttpExceptionFilter,
    },
    {
      provide: APP_FILTER,
      useClass: MongooseExceptionFilter,
    },
    {
      provide: APP_FILTER,
      useClass: MongodbExceptionFilter,
    },
  ],
})
export class AppModule {}
